package com.java.jvalidator.framework.config;

import java.util.HashMap;
import java.util.Map;

import com.java.jvalidator.framework.ValidationException;
import com.java.jvalidator.framework.ValidationResult;

public class ValidationConfig {
	private Map<String, ClassConfig> config = new HashMap<String, ClassConfig>();

	private Map<String, RuleComposite> ruleComposite = new HashMap<String, RuleComposite>();

	private XMLConfigFileParser parser = new DOMParser();

	private static ValidationConfig instance = new ValidationConfig();

	private ValidationConfig() {
		try {
			// 如果配置有rule-composite.xml，加载转换该xml
			initialize();
		} catch (ValidationException e) {
			e.printStackTrace();
		}
	}

	public static ValidationConfig getInstance() {
		return instance;
	}

	void initialize() throws ValidationException {
		this.ruleComposite = this.parser.parseRuleComposite();
	}

	ValidationResult validate(Object target) throws ValidationException {
		return validate(target, null);
	}

	public ValidationResult validate(Object target, String propertyPattern) throws ValidationException {
		ClassConfig classConfig = getClassConfig(target.getClass().getName());
		if (classConfig == null) {
			throw new ValidationException("The config file doesn't exist for the class:");
		}
		return classConfig.validate(target, propertyPattern);
	}

	public void configValidator(String className, String propertyName, String validatorClassName, Parameters params) throws ValidationException {
		ClassConfig classConfig = getClassConfig(className);
		if (classConfig == null) {
			throw new ValidationException("The config file doesn't exist for the class:");
		}
		classConfig.configCustomValidator(propertyName, validatorClassName, params);
	}

	private synchronized ClassConfig getClassConfig(String className) throws ValidationException {
		ClassConfig classConfig = (ClassConfig) this.config.get(className);
		if (classConfig == null) {
			classConfig = this.parser.parseClassConfig(className);
			this.config.put(className, classConfig);
		}
		return classConfig;
	}

	public void setPlaceHolderValue(Class<?> clazz, String propertyName, String errorMsgName, String[] strings) throws ValidationException {
		if ((clazz == null) || (propertyName == null) || (errorMsgName == null)) {
			return;
		}
		ClassConfig config = (ClassConfig) this.config.get(clazz.getName());
		if (config == null) {
			config = getClassConfig(clazz.getName());
			if (config == null) {
				throw new ValidationException("The config file doesn't exist for the class:");
			}
		}
		config.setPlaceHolderValues(propertyName, errorMsgName, strings);
	}

	void addRuleComposite(RuleComposite comp) {
		if (comp == null) {
			return;
		}
		this.ruleComposite.put(comp.getId(), comp);
	}

	RuleComposite getRuleComposite(String id) {
		if (id == null) {
			return null;
		}
		return (RuleComposite) this.ruleComposite.get(id);
	}
}
